#!/usr/bin/env python
# encoding: utf-8

from source.Lib import orm, Tools
from pprint import pprint
import datetime
import json


def main():
    session = orm.Session()
    # code -> [name, ...]
    # {name -> count}
    # {code >> max(name)}.values()
    industrys = dict()
    codes = dict()
    for i in session.query(orm.Industry).all():
        if i.name in ('上证指数', '沪市A股', '沪深A股', '深市B股', '小盘', '深证综指', '新三板', '沪深300', '股权激励', 'B股', 'A股',
                      '创业板', '次新股', '基金重仓', '大盘', '中盘', '成渝特区', '新疆', '粤港澳', '股权转让', '高派息', '深市A股',
                      '北京', '天津', '上海', '重庆', '河北', '山西', '辽宁', '吉林', '黑龙江', '江苏', '西藏', '高送转', '贵州',
                      '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '海南', '四川', '长株潭', '次新开板'
                      '贵州', '云南', '陕西', '甘肃', '青海', '台湾', '新疆', '京津冀', '其它行业', '增持回购', '沪市B股', '社保重仓',
                      '沪深B股', '沪股通', '深圳', '中证500', '举牌', '内蒙古', '创投概念', '券商重仓', '含H股', '广西', '雄安新区',
                      '深股通', '深证成指', '创业', '百元股', '次新开板', '融资融券', '重组概念', '陕甘宁', '皖江区域', '陕甘宁'):
            continue
        name = industry_replace(i.name)
        industrys[name] = {'data': i.codes, 'count': len(i.codes)}
        for j in i.codes:
            codes.setdefault(j, list())
            codes[j].append(name)

    session.query(orm.NewIndustry).delete()
    session.commit()

    codes_max_industry = dict()
    for i in codes:
        codes_max_industry.setdefault(i, {'count': len(industrys[codes[i][0]]), 'name': codes[i][0]})
        for j in codes[i]:
            volume = len(industrys[j])
            if volume > codes_max_industry[i]['count']:
                codes_max_industry[i]['count'] = volume
                codes_max_industry[i]['name'] = j

    new_industrys = dict()
    for code in codes_max_industry:
        new_industrys.setdefault(codes_max_industry[code]['name'], [])
        new_industrys[codes_max_industry[code]['name']].append(code)
        codes_max_industry[code] = codes_max_industry[code]['name']

    for name in new_industrys:
        session.add(orm.NewIndustry(name=name, codes=new_industrys[name]))
    session.commit()

    industry_rate_disbut = dict()
    for code in codes_max_industry:
        industry_rate_disbut.setdefault(codes_max_industry[code], 0)
        industry_rate_disbut[codes_max_industry[code]] += 1

    cli = Tools.Outer().get_cli()
    st_datetime = datetime.datetime.strptime("2000-01-01", '%Y-%m-%d')
    ed_datetime = datetime.datetime.now()
    jump = 0
    while st_datetime <= ed_datetime and jump <= 10:
        search_date = ed_datetime.strftime("%Y-%m-%d")
        if not len(cli.keys(f'AMM:{search_date}:*')):
            jump = 0
            total_industry = dict()  # date->name-> 换手率, 成交量, 成交金额, 股票数量, 流通市值
            for info in session.query(orm.StockDay).filter(orm.StockDay.date == search_date).all():
                try:
                    industry = codes_max_industry[info.code]
                except (KeyError, ):
                    industry = '其他行业'
                total_industry.setdefault(industry, {'turnover': 0, 'voturnover': 0, 'vaturnover': 0, 'mcap': 0, 'count': 0})
                total_industry[industry]['count'] += 1
                total_industry[industry]['turnover'] += info.turnover
                total_industry[industry]['voturnover'] += info.voturnover
                total_industry[industry]['vaturnover'] += info.vaturnover
                total_industry[industry]['mcap'] += info.mcap

            for industry in total_industry:
                total_industry[industry]['turnover'] = round(
                    total_industry[industry]['turnover'] / total_industry[industry]['count'], 1)

            print(search_date, end=':')
            for industry in total_industry:
                cli.set(f'AMM:{search_date}:{industry}', json.dumps(total_industry[industry]))
                print(industry, end=' ')
            print()
        else:
            jump += 1
        ed_datetime -= datetime.timedelta(days=1)


def industry_replace(name):
    for field, new_field in [
        ('QFII', ''),
        ('机械', ''),
        ('综合', ''),
        ('娱乐', ''), ('游戏', '娱乐'), ('体育', '娱乐'), ('旅游', '娱乐'), ('传媒', '娱乐'), ('传播指数', '娱乐'),
        ('金属', '材料'), ('石墨烯', '材料'), ('塑料', '材料'), ('半导体', '材料'), ('稀缺资源', '材料'), ('采掘', '材料'),
        ('可燃冰', '材料'), ('钢铁', '材料'), ('黄金', '材料'), ('煤炭', '材料'), ('水泥行业', '材料'), ('材料', ''),
        ('充电桩', '能源'), ('电池', '能源'), ('核电核能', '能源'), ('石油行业', '能源'), ('油气改革', '能源'), ('燃气', '能源'),
        ('太阳能', '能源'), ('电力', '能源'), ('风能', '能源'), ('农林', ''), ('页岩气', '能源'), ('能源', ''),
        ('渔业', '农林'), ('农业', '农林'), ('林业', '农林'), ('畜牧业', '农林'), ('猪肉', '农林'),
        ('食品', '农林'), ('饮料', '农林'),
        ('环保', ''), ('环保', ''), ('污水处理', '环保'), ('空气治理', '环保'),
        ('军工', ''), ('军民融合', '军工'),
        ('化工', ''), ('化学', '化工'), ('固废处理', '化工'),
        ('基础建设', '建筑'), ('装饰园林', '建筑'), ('建筑', '建筑'), ('园林工程', '建筑'),
        ('工业', ''), ('制造', '工业'),
        ('设备', '制造'), ('视听器材', '制造'), ('家用轻工', '制造'), ('仪器仪表', '制造'), ('汽车', '制造'),
        ('纺织', '制造'), ('服装', '制造'),
        ('航空', ''), ('飞机', '航空'), ('航运', '航空'),
        ('运输', '公共'), ('铁路', '公共'), ('交通', '公共'), ('服务', '公共'), ('通信', '公共'),
        ('房地产', ''), ('地产指数', '房地产'),
        ('医药', ''), ('基因', '医药'), ('医疗器械', '医药'), ('生物疫苗', '医药'), ('细胞治疗', '医药'), ('二胎', '医药'),
        ('云计算', 'IT'), ('大数据', 'IT'), ('互联', 'IT'), ('智慧', 'IT'), ('智能', 'IT'), ('信息安全', 'IT'),
        ('华为概念', 'IT'), ('物联网', 'IT'), ('特斯拉', 'IT'), ('国产软件', 'IT'), ('计算机', 'IT'), ('网络', 'IT'),
        ('三星', 'IT'), ('芯片', 'IT'), ('卫星导航', 'IT'), ('电子', 'IT'), ('电器', 'IT'), ('阿里', 'IT'),
        ('三网融合', 'IT'), ('区块链', 'IT'),
        ('证券', '金融'), ('O2O模式', '金融'), ('PPP概念', '金融'), ('一带一路', '金融'), ('证券', '金融'),
        ('银行', '金融'), ('中药', '医药'), ('业绩', '金融'), ('上海自贸', '金融'),
        ('商业', '金融'), ('保险', '金融'), ('信托', '金融'), ('养老', '金融'), ('金融', '金融'), ('海南自贸', '金融'),
        ('零售', '金融'), ('批零指数', '金融'), ('经济', '金融'), ('百货O2O', '金融'), ('中小企业', '金融'), ('自贸区', '金融'),
        ('海峡西岸', '金融'), ('海工装备', '金融'), ('丝绸之路', '金融'), ('预盈预增', '金融'),
        ('专业工程', '其他行业'), ('仓储业', '其他行业'), ('准ST股', '其他行业'), ('证金汇金', '其他行业'), ('前海概念', '其他行业'),
        ('本月解禁', '其他行业'), ('旅馆业', '其他行业'),
        ('中科院系', '教育'), ('高校', '教育'),
    ]:
        if field in name:
            if new_field:
                return new_field
            else:
                return field
    return name


if __name__ == '__main__':
    main()
